let modules = import.meta.glob("../views/**/*.vue");
const main = () => import("@/views/Main.vue");
function menuTree(data) {
  const resArr = [];

  data.map((item) => {
    if (item.menuParentId === 0) {
      resArr.push({
        ...item,
        children: [],
      });
    } else {
      _dfs(resArr, item);
    }
  });

  return routerObj(resArr);
}

function _dfs(resArr, data) {
  if (!resArr.length) return;
  if (!data.menuParentId) return;
  if (!data.id) return;
  resArr.map((item) => {
    if (item.id === data.menuParentId) {
      item.children.push({
        ...data,
        children: [],
      });
    } else {
      if (item.children.length) _dfs(item.children, data);
    }
  });
}

function routerObj(data) {
  return data.map((item) => {
    const {
      menuName,
      menuPath,
      menuComponent,
      menuRouterName,
      menuIcon,
      menuType,
    } = item;
    const obj = {
      name: menuRouterName,
      path: menuPath,
      component: modules[".." + menuComponent + ".vue"] ?? main,
      redirect: menuType === 1 ? menuPath : "",
      icon: menuIcon,
      menuType,
      meta: {
        title: menuName,
        name: menuRouterName,
        requiresAuth: true,
      },
    };
    if (item.children && item.children.length > 0) {
      obj.children = routerObj(item.children);
    }
    return obj;
  });
}

export { menuTree, routerObj };
